import { useAxios } from '@hooks/useAxios'
import { API_UPLOAD_URL } from '@services/baseApi'
import { useRef, useState } from 'react'

export const useUpload = ({ onSuccess }) => {
  const { http } = useAxios()
  const keyRef = useRef()
  const [loading, setLoading] = useState({})
  const clickRef = useRef(null) // 点击触发文件选择框的元素

  function handleInputChange(e) {
    const file = e.target.files[0]

    const formData = new FormData()
    formData.append('file', file)

    http
      .post(API_UPLOAD_URL, formData)
      .then((res) => onSuccess?.(clickRef.current, res, file))
      .finally(() => setLoading((prev) => ({ ...prev, [keyRef.current]: false })))
  }

  const onClick = (e) => {
    const target = e.target instanceof HTMLButtonElement ? e.target : e.target.closest('button')
    clickRef.current = target
    const key = target.dataset.key
    keyRef.current = key
    setLoading((prev) => ({ ...prev, [key]: true }))

    const input = document.createElement('input')
    input.type = 'file'
    input.onchange = handleInputChange
    input.click()
  }
  return { loading, onClick }
}
